package core

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"server/client/casbin"
	"server/client/db"
	"server/client/jwt"
	"server/config"
	"time"
)

type ApiServer struct {
	r *gin.Engine
}

func (a ApiServer) PrepareRun() error {

	//初始化数据库
	db.InitMysql(config.GlobalConf.Mysql)
	// 初始化数据库表结构
	db.MysqlTables(db.DB)
	if config.GlobalConf.System.UseMultipoint {
		db.InitRedis(config.GlobalConf.Redis)
	}

	//初始化jwt client
	jwt.InitJwt(config.GlobalConf.Jwt.SigningKey)

	// 初始化 casbin client
	casbin.InitCasbin(db.DB)

	//初始化ssh client
	//初始化 http client
	//初始化k8s client

	db.SetTableData(db.DB)
	return nil
}

func (a ApiServer) Run() error {
	// 端口监听；tls cert加载

	address := fmt.Sprintf(":%s", config.GlobalConf.System.Port)
	s := &http.Server{
		Addr:           address,
		Handler:        a.r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	if config.GlobalConf.System.IsTls {
		log.Fatal(s.ListenAndServeTLS(config.GlobalConf.System.CertFile, config.GlobalConf.System.KeyFile))
	} else {
		log.Fatal(s.ListenAndServe())
	}
	return nil
}

func NewApiServer() (*ApiServer, error) {
	//初始化路由
	return &ApiServer{
		r: initRouters(),
	}, nil
}
